package com.yztstudy.Service.Impl;

import com.yztstudy.Entity.Cart;
import com.yztstudy.Entity.Desk;
import com.yztstudy.Entity.Item;
import com.yztstudy.Entity.Order;
import com.yztstudy.Mapper.OrderMapper;
import com.yztstudy.Service.*;
import com.yztstudy.Utils.CartsTotalPriceUtils;
import com.yztstudy.Utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private DeskService deskService;

    @Autowired
    private ItemService itemService;

    @Override
    public Integer addOrder(Integer deskID) {
        //1.获取当前餐桌的所有菜品和餐桌
        List<Cart> carts = cartService.getCarts(deskID);
        Desk desk = deskService.getDeskByID(deskID);

        //2.创建订单
        Order order = new Order();
        order.setDesk(desk);
        order.setState(0);
        order.setOrder_time(TimeUtils.currentTime());
        order.setTotalFee(CartsTotalPriceUtils.getTotalPrice(carts));

        //3.新增订单(需要order表的主键)
        int result = orderMapper.addOrder(order);
        if (result == 0){
            return 0;
        }

        //4.新增详情表
        int index = 0;
        for (Cart cart : carts)
        {
            Item item = new Item();
            item.setOrder(order);
            item.setFood(cart.getFood());
            item.setNum(cart.getNum());
            result = itemService.addItem(item);
            if (result == 0)
            {
                return 0;
            }
            index++;
        }

        //5.预定餐桌成功
        desk.setBookTime(order.getOrder_time());
        result = deskService.orderState(desk);
        if (result == 0)
        {
            return 0;
        }

        return 2 + index; //返回受影响的总行数
    }

    @Override
    public List<Order> getAllOrders() {
        return orderMapper.getAllOrders();
    }

    @Override
    public Integer pay(Integer deskID, Integer Oid) {

        int result = 0;
        //1.根据deskID删除购物车里面的所有内容
        result = cartService.deleteCarts(deskID);
        if (result == 0)
        {
            return 0;
        }

        //2.根据Oid，删除所有的items
        result = itemService.deleteItemsByOrderId(Oid);
        if (result == 0)
        {
            return 0;
        }

        //3.根据Oid，删除对应的Order
        result = orderMapper.deleteByOid(Oid);
        if (result == 0)
        {
            return 0;
        }

        return result;
    }
}
